package com.me.modules.knowledge.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.me.modules.common.annotation.SysLog;
import com.me.modules.common.controller.BaseController;
import com.me.modules.common.page.Page;
import com.me.modules.common.utils.*;
import com.me.modules.sys.entity.FieldDictionaryEntity;
import com.me.modules.sys.entity.OperationEntity;
import com.me.modules.sys.entity.ValueDictionaryEntity;
import com.me.modules.sys.service.FieldDictionaryService;
import com.me.modules.sys.service.OperationService;
import com.me.modules.sys.service.ValueDictionaryService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import com.me.modules.knowledge.entity.KnowledgeInfoEntity;
import com.me.modules.knowledge.service.KnowledgeInfoService;

import javax.servlet.http.HttpServletRequest;


/**
 * 知识工单信息表
 *
 * @author me
 * @email me@163.com
 * @date 2019-01-04 13:34:33
 */
@Controller
@RequestMapping("/knowledge")
public class KnowledgeInfoController extends BaseController {
    @Autowired
    private KnowledgeInfoService knowledgeInfoService;
    @Autowired
    FieldDictionaryService fieldDictionaryService;
    @Autowired
    ValueDictionaryService valueDictionaryService;
    @Autowired
    private OperationService operationService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("knowledgeinfo:all")
    @SysLog("查看知识列表")
    public String list(KnowledgeInfoEntity knowledgeInfoEntity, Model model, HttpServletRequest request) {

        int pageNum = Utils.parseInt(request.getParameter("pageNum"), 1);
        Page<KnowledgeInfoEntity> page = knowledgeInfoService.findPage(knowledgeInfoEntity, pageNum);
        List<KnowledgeInfoEntity> knowledgeList = page.getResult();
        List<KnowledgeInfoEntity> newKnowledgeList = new ArrayList<>();
        List<FieldDictionaryEntity> fieldList = fieldDictionaryService.queryByTableName("knowledge");
        if (fieldList.size() > 0) {
            if (knowledgeList.size() > 0) {
                for (KnowledgeInfoEntity KnowledgeInfo : knowledgeList) {
                    String tableId = KnowledgeInfo.getId().toString();
                    List<ValueDictionaryEntity> valueList = new ArrayList<>();
                    for (FieldDictionaryEntity fieldDictionaryEntity : fieldList) {
                        Long fieldID = fieldDictionaryEntity.getId();
                        ValueDictionaryEntity value = valueDictionaryService.findByFieldIdAndUserId(fieldID, tableId);
                        if (value != null) {
                            valueList.add(value);
                        } else {
                            valueList.add(new ValueDictionaryEntity());
                        }
                    }
                    KnowledgeInfo.setValueDictionarys(valueList);
                    knowledgeList.add(KnowledgeInfo);
                }
            }
            model.addAttribute("page", new Page(newKnowledgeList, page.getTotal(), page.getPageSize(), page.getPageNum()));

        } else {
            model.addAttribute("page", page);
        }

        model.addAttribute("knowledge", knowledgeInfoEntity);
        model.addAttribute("fieldList", fieldList);

        return "knowledge/knowledge";
    }


    /**
     * 信息
     */

    @RequestMapping("/info")
    @RequiresPermissions("knowledgeinfo:all")
    @SysLog("查看知识工单信息")
    public String info(Model model, String id, HttpServletRequest request) {
        List<FieldDictionaryEntity> fieldList = fieldDictionaryService.queryByTableName("knowledge");
        if (!StringUtils.isEmpty(id)) {
            KnowledgeInfoEntity knowledgeInfo = knowledgeInfoService.queryObject(id);
            if (fieldList != null && fieldList.size() > 0) {
                String tableId = knowledgeInfo.getId().toString();
                List<ValueDictionaryEntity> valueList = new ArrayList<>();
                for (FieldDictionaryEntity fieldDictionaryEntity : fieldList) {
                    Long fieldID = fieldDictionaryEntity.getId();
                    ValueDictionaryEntity value = valueDictionaryService.findByFieldIdAndUserId(fieldID, tableId);
                    if (value != null) {
                        valueList.add(value);
                    } else {
                        valueList.add(new ValueDictionaryEntity());
                    }
                }
                knowledgeInfo.setValueDictionarys(valueList);
            }

            model.addAttribute("knowledge", knowledgeInfo);
        }
        model.addAttribute("fieldList", fieldList);
        //查询业务系统
        List<OperationEntity> operationList = operationService.queryListByBean(new OperationEntity());
        model.addAttribute("operationTree", JsonUtil.getJsonByObj(operationList));
        return "knowledge/knowledgeEdit";


    }

    /**
     * 编辑
     *
     * @param knowledgeInfoEntity
     * @return
     */
    @RequestMapping(value = "edit", method = RequestMethod.POST)
    @RequiresPermissions("knowledgeinfo:all")
    @ResponseBody
    public Result edit(KnowledgeInfoEntity knowledgeInfoEntity) {
        if (StringUtils.isEmpty(knowledgeInfoEntity.getId())) {
            try {
                knowledgeInfoEntity.setKnoNo(Utils.getSN("kno_", "yyyyMMddHHmmss", 2));
                knowledgeInfoEntity.setStatus("0");
                knowledgeInfoEntity.setAuthorId(UserUtils.getCurrentUser().getId());
                knowledgeInfoEntity.setCreateDate(new Date());
                knowledgeInfoService.save(knowledgeInfoEntity);
                if (knowledgeInfoEntity.getValueDictionarys().size() > 0) {
                    for (ValueDictionaryEntity value : knowledgeInfoEntity.getValueDictionarys()) {
                        if (!StringUtils.isEmpty(value.getFieldValue())) {
                            value.setTableId(knowledgeInfoEntity.getId().toString());
                            valueDictionaryService.save(value);
                        }
                    }
                }
                return Result.ok("保存知识工单成功!");
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error("保存知识工单失败!请联系管理员");
            }
        } else {
            try {
                knowledgeInfoService.update(knowledgeInfoEntity);
                if (knowledgeInfoEntity.getValueDictionarys().size() > 0) {
                    for (ValueDictionaryEntity value : knowledgeInfoEntity.getValueDictionarys()) {
                        ValueDictionaryEntity valueDictionaryEntity = valueDictionaryService
                                .findByFieldIdAndUserId(value.getFieldId(), knowledgeInfoEntity.getId().toString());
                        if (valueDictionaryEntity != null) {
                            valueDictionaryService.delete(valueDictionaryEntity.getId());
                        }
                        if (!StringUtils.isEmpty(value.getFieldValue())) {
                            value.setTableId(knowledgeInfoEntity.getId().toString());
                            valueDictionaryService.save(value);
                        }
                    }
                }
                return Result.ok("修改知识工单成功!");
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error("修改知识工单失败!请联系管理员");
            }
        }
    }

//	/**
//	 * 保存
//	 */
//	@RequestMapping("/save")
//	@RequiresPermissions("knowledgeinfo:all")
//	public Result save(@RequestBody KnowledgeInfoEntity knowledgeInfo){
//		knowledgeInfoService.save(knowledgeInfo);
//
//		return Result.ok();
//	}

    /**
     * 修改
     */
//	@RequestMapping("/update")
//	@RequiresPermissions("knowledgeinfo:update")
//	public Result update(@RequestBody KnowledgeInfoEntity knowledgeInfo){
//		knowledgeInfoService.update(knowledgeInfo);
//
//		return Result.ok();
//	}

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("knowledgeinfo:all")
    @ResponseBody
    @SysLog("删除知识工单")
    public Result delete(String id) {
        try {
            if (knowledgeInfoService.delete(id) < 1) {
                return Result.error("删除知识工单失败!请联系管理员");
            }
            return Result.ok("删除知识工单成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除知识工单失败!请联系管理员");
        }
    }

    /**
     * 查询发布知识列表
     */
    @RequestMapping("/search")
    @RequiresPermissions("knowledge:search")
    @SysLog("查询发布知识列表")
    public String search(KnowledgeInfoEntity knowledgeInfoEntity, Model model, HttpServletRequest request) {
        int pageNum = Utils.parseInt(request.getParameter("pageNum"), 1);
        Page<KnowledgeInfoEntity> page = knowledgeInfoService.searchList(knowledgeInfoEntity, pageNum);
        List<KnowledgeInfoEntity> knowledgeList = page.getResult();
        List<KnowledgeInfoEntity> newKnowledgeList = new ArrayList<>();
        List<FieldDictionaryEntity> fieldList = fieldDictionaryService.queryByTableName("knowledge");
        if (fieldList.size() > 0) {
            if (knowledgeList.size() > 0) {
                for (KnowledgeInfoEntity KnowledgeInfo : knowledgeList) {
                    String tableId = KnowledgeInfo.getId().toString();
                    List<ValueDictionaryEntity> valueList = new ArrayList<>();
                    for (FieldDictionaryEntity fieldDictionaryEntity : fieldList) {
                        Long fieldID = fieldDictionaryEntity.getId();
                        ValueDictionaryEntity value = valueDictionaryService.findByFieldIdAndUserId(fieldID, tableId);
                        if (value != null) {
                            valueList.add(value);
                        } else {
                            valueList.add(new ValueDictionaryEntity());
                        }
                    }
                    KnowledgeInfo.setValueDictionarys(valueList);
                    knowledgeList.add(KnowledgeInfo);
                }
            }
            model.addAttribute("page", new Page(newKnowledgeList, page.getTotal(), page.getPageSize(), page.getPageNum()));

        } else {
            model.addAttribute("page", page);
        }

        model.addAttribute("knowledge", knowledgeInfoEntity);
        model.addAttribute("fieldList", fieldList);

        return "knowledge/searchList";
    }

    /**
     * 查询发布知识列表
     */
    @RequestMapping("/view")
    @RequiresPermissions("knowledge:search")
    @SysLog("查询发布知识信息")
    public String knowledgeView(Model model, String id, HttpServletRequest request) {
        List<FieldDictionaryEntity> fieldList = fieldDictionaryService.queryByTableName("knowledge");
        if (!StringUtils.isEmpty(id)) {
            KnowledgeInfoEntity knowledgeInfo = knowledgeInfoService.queryObject(id);
            int count = knowledgeInfo.getViewCount() + 1;
            knowledgeInfo.setViewCount(count);
            knowledgeInfoService.update(knowledgeInfo);
            if (fieldList != null && fieldList.size() > 0) {
                String tableId = knowledgeInfo.getId().toString();
                List<ValueDictionaryEntity> valueList = new ArrayList<>();
                for (FieldDictionaryEntity fieldDictionaryEntity : fieldList) {
                    Long fieldID = fieldDictionaryEntity.getId();
                    ValueDictionaryEntity value = valueDictionaryService.findByFieldIdAndUserId(fieldID, tableId);
                    if (value != null) {
                        valueList.add(value);
                    } else {
                        valueList.add(new ValueDictionaryEntity());
                    }
                }
                knowledgeInfo.setValueDictionarys(valueList);
            }

            model.addAttribute("knowledge", knowledgeInfo);
        }
        model.addAttribute("fieldList", fieldList);

        return "knowledge/knowledgeView";
    }

}
